package top.yongyan0624.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import top.yongyan0624.pojo.Books;
import top.yongyan0624.service.BookService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Yongyan
 * @description: TODO
 * @date 2020/12/20
 **/
@Controller
@RequestMapping("/book")
public class BookController {

    @Resource(name = "BookServiceImpl")
    private BookService bookService;

    //查询全部书籍，存入model中的键值对中，并且返回一个展示页面文件名用来跳转到展示页面
    @RequestMapping("/toAllBookPage")
    public String queryBookAll(Model model){

        List<Books> bookList = bookService.queryBookAll();
        model.addAttribute("bookList",bookList);

        return "allBookPage";
    }

    //跳转到添加书籍页面
    @RequestMapping("/toAddBookPage")
    public String toAddBookPage(){
        return "addBookPage";
    }

    //添加书籍
    @RequestMapping("/addBook")
    public String addBook(Books book){
        System.out.println("添加了一个book==> "+book);
        bookService.addBook(book);

        return "redirect:/book/toAllBookPage";    //重定向到 @RequestMapping("/allBook") 请求
    }

    //跳转到修改书籍页面
    @RequestMapping("/toUpdateBookPage/{bookID}")
    public String toUpdateBookPage(@PathVariable("bookID") int bookID, Model model){
        Books book = bookService.queryBookById(bookID);
        model.addAttribute("book",book);

        return "updateBookPage";
    }

    //修改书籍
    @RequestMapping("/updateBook")
    public String updateBook(Books book){
        int i = bookService.updateBook(book);
        if (i>0){
            System.out.println(book.getBookID()+" 修改成功");
        }
        return "redirect:/book/toAllBookPage";
    }

    //删除书籍
    @RequestMapping("/deleteBook/{bookID}")
    public String deleteBook(@PathVariable("bookID") int bookID){
        int i = bookService.deleteBook(bookID);
        if (i>0){
            System.out.println(bookID +" 删除成功");
        }
        return "redirect:/book/toAllBookPage";
    }

    //查询单个书籍
    @RequestMapping("/queryBookById")
    public String queryBookById(String bookName,Model model){
        Books book = bookService.queryBookByName(bookName);
        List<Books> bookList = new ArrayList<Books>();
        if (book != null){
            bookList.add(book);
        } else {
            bookList = bookService.queryBookAll();
            model.addAttribute("error","未找到该书籍...");
        }

        model.addAttribute("bookList",bookList);

        return "allBookPage";
    }
}
